#include <QtGui>
#include "chatingtab.h"
#include "ui_conversation.h"

const static int MAX_VISIBLE_MESSAGES = 100;
const static QString CONVERSATION_TEMPLATE = "<p><b>%1:</b><br/>%2</p>";

ChatingTab::ChatingTab(const QString &ip):
    QWidget(0),
    mUi(new Ui::Conversation),
    mIp(ip)
{
    mUi->setupUi(this);
    mUi->splitter->setStretchFactor(0,5); // Converstion board
    mUi->splitter->setStretchFactor(1,1); // Text editor

    connect(mUi->sendButton, SIGNAL(clicked()),
            this, SLOT(onSendMessage()));
}

ChatingTab::~ChatingTab()
{
    delete mUi;
}

void ChatingTab::updateMessage(const QList<recordInfo> &messageList)
{
    QString htmlText;
    convertMessageToHtml(messageList, htmlText);
    mUi->conversationBoard->setHtml(htmlText);

    moveToLastLine();
}

void ChatingTab::convertMessageToHtml(const QList<recordInfo> &messageList, QString &outputHtml)
{
    int length = messageList.size();
    int beginIndex = std::max(0, length - MAX_VISIBLE_MESSAGES);

    outputHtml.clear();
    outputHtml.append("<html><body style=\"font-size:14px\">");
    for (int index = beginIndex; index < length; ++index)
    {
        const recordInfo &item = messageList[index];
        outputHtml.append(CONVERSATION_TEMPLATE.arg(item.getName(), item.getContent()));
    }
    outputHtml.append("</body></html>");
}

void ChatingTab::moveToLastLine()
{
    QTextCursor textCursor;
    textCursor = mUi->conversationBoard->textCursor();
    textCursor.movePosition(QTextCursor::End);
    mUi->conversationBoard->setTextCursor(textCursor);
}

void ChatingTab::onSendMessage()
{
    const QString & text = mUi->writingBoard->toPlainText();
    if (! text.isEmpty())
    {
        emit sendMessage(mIp, text);
    }
    mUi->writingBoard->clear();
}
